$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_yzhtbcxy_m")
    const dgrid1 = $NG.getCmpApi("p_form_yzhtbcxy_d1")
    const toolbar_d3 = $NG.getCmpApi("toolbar_p_form_yzhtbcxy_d3")
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    const user = $NG.getUser()
    toolbar_d3.insert({
        id: "dowloadFile",
        text: "下载导入模板",
        iconCls: "icon-New"
    });
    useClick(()=>{
        getFileId()
    },"dowloadFile")
    useValuesChange(() => {
        const PhidCnt = mstform.getItem("u_htmc").getValue()
        if (!PhidCnt) return
        const datas = mstform.getItem("u_htmc").getOrigin()
        $NG.execServer("getCntCbInfoByPhid", { phid: PhidCnt }, (res) => {
            if (res.count == 0) {
                return
            }
            const datas = JSON.parse(res.data)[0].extendObjects
            console.log(`datas`, datas);
            const arr = [
                {
                    key: 'u_xmssdw',
                    value: {
                        value: datas.xmssdw_phid,
                        label: datas.xmssdw_name
                    }
                },
                {
                    key: 'u_jfdw',
                    value: {
                        value: datas.jfdw_phid,
                        label: datas.jfdw_name
                    }
                },
                {
                    key: 'u_htje',
                    value: datas.Cnt_sum_vat_fc
                },
                {
                    key: 'bill_no',
                    value: datas.cnt_no
                },
            ]
            setHeadValues(arr)
        })

    }, "p_form_yzhtbcxy_m.u_htmc")

    // 表头批量赋值
    function setHeadValues(arr) {
        arr.forEach(item => {
            mstform.getItem(item.key)?.setValue(item.value)
        })
    }
    // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: 'b3241071-180e-4b37-9f43-d4535b321fd4' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()

    }
})